package com.wkbb.basic.controller.manage;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.service.*;
import com.wkbb.basic.thread.ImportTeacherTask;
import com.wkbb.basic.thread.XmppUpdatePersonByDateTask;
import com.wkbb.basic.vo.EmployeeEditInfoVo;
import com.wkbb.basic.vo.TeacherManageVo;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.EmployeeInfoDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.enums.RoleTypeEnum;
import com.wkbb.common.enums.UserTypeEnum;
import com.wkbb.common.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionException;

/**
 * @author dengjingyuan
 * @date
 */
@RestController
@Api(description = "老师管理(后台管理)")
@RequestMapping("/basic/{apiVersion}/teacher/manage")
@Slf4j
public class TeacherManageController extends BaseController {

    @Autowired
    private TeacherManageService teacherManageService;

    @Autowired
    private UserService userService;

    @Autowired
    @Lazy
    private XmppService xmppService;

    @Autowired
    private UserOpenService userOpenService;

    private static final Integer PAGE_SIZE = 100;

    private static final Integer MAX_IMPORT_NUM_OF_CLEAR_ADDRESS_BOOK = 20;//一次性导入老师数量超过这个值，就不再单个清理通讯录缓存

    @ApiOperation(value = "新增老师")
    @RequestMapping(value = "/addTeacher", method = RequestMethod.POST)
    public ResultDTO<Object> addTeacher(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @RequestBody EmployeeInfoDto employeeInfoDto) {
        log.info("***********TeacherManageController.addTeacher******...apiVersion:{},Employee:{}", apiVersion, employeeInfoDto);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        if (checkData(employeeInfoDto)) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            ErrorCode result = userService.checkMobileErrorCode(employeeInfoDto.getMobile(), employeeInfoDto.getCardNo(),
                    employeeInfoDto.getJobNo(), (employeeInfoDto.getUserId() == null || employeeInfoDto.getUserId() == 0) ? null : employeeInfoDto.getUserId(),
                    RoleTypeEnum.TEACHER.getValue(), employeeInfoDto.getOrgId(), employeeInfoDto.getAccount(),null);
            if (result != null) {
                return new ResultDTO<>(result);
            }

            //判断当前学校学校是否有已有该老师用户
            if (employeeInfoDto.getUserId() != null && employeeInfoDto.getUserId() != 0) {
                Map<String, Object> params = new HashMap<>(2);
                params.put("orgId", employeeInfoDto.getOrgId());
                params.put("userId", employeeInfoDto.getUserId());
                List<TeacherManageVo> allTeacherManageList = teacherManageService.getAllTeacherManageList(params);
                if (allTeacherManageList != null && !allTeacherManageList.isEmpty()) {
                    return new ResultDTO<>(ErrorCode.EMPLOYEE_EXISTS);
                }
            }

            Long userId = teacherManageService.insertTeacher(employeeInfoDto, userDto.getName(),true,true);

            //返回用户Id
            return new ResultDTO<>(userId);
        } catch (Exception e) {
            log.error("***********TeacherManageController.addTeacher******", e);
            return new ResultDTO<>(false);
        }
    }

    /**
     * 检查必填项
     *
     * @param employeeInfoDto 老师信息
     * @return 检查是否未通过
     */
    private boolean checkData(EmployeeInfoDto employeeInfoDto) {
        return employeeInfoDto.getOrgId() == null || employeeInfoDto.getOrgId() == 0
//                || StringUtil.isNullOrBlank(employeeInfoDto.getOrgName())
                || StringUtil.isNullOrBlank(employeeInfoDto.getMobile())
                || StringUtil.isNullOrBlank(employeeInfoDto.getName());
    }

    @ApiOperation(value = "修改老师")
    @RequestMapping(value = "/updateTeacher", method = RequestMethod.PUT)
    public ResultDTO<EmployeeInfoDto> updateTeacher(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @RequestBody EmployeeInfoDto employeeInfoDto) {
        log.info("***********TeacherManageController.updateTeacher******...apiVersion:{},Employee:{}", apiVersion, employeeInfoDto);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        if (employeeInfoDto.getId() == null || employeeInfoDto.getId() == 0
                || employeeInfoDto.getUserId() == null || employeeInfoDto.getUserId() == 0
                || checkData(employeeInfoDto)) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            //后台不会修改手机号
            ErrorCode result = userService.checkMobileErrorCode(employeeInfoDto.getMobile(), employeeInfoDto.getCardNo(), employeeInfoDto.getJobNo(),
                    employeeInfoDto.getUserId(), RoleTypeEnum.TEACHER.getValue(), employeeInfoDto.getOrgId(), employeeInfoDto.getAccount(),null);
            if (result != null) {
                return new ResultDTO<>(result);
            }

            return teacherManageService.updateTeacher(employeeInfoDto, userDto.getName(), true,true);
        } catch (Exception e) {
            log.error("***********TeacherManageController.updateTeacher******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "删除老师")
    @RequestMapping(value = "/deleteTeacher", method = RequestMethod.DELETE)
    public ResultDTO deleteTeacher(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "老师表id",  required = true) @RequestParam(name = "id", required = true) List<Long> ids) {
        log.info("***********TeacherManageController.deleteTeacher******...apiVersion:{},ids:{}", apiVersion, Arrays.toString(ids != null ? ids.toArray() : new Object[0]));

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }
        try {
            if (ids == null || ids.isEmpty()) {
                return new ResultDTO<>();
            }
            return teacherManageService.deleteTeacher(ids, userDto.getName());
        } catch (Exception e) {
            log.error("***********TeacherManageController.deleteTeacher******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "查询老师详情")
    @RequestMapping(value = "/getTeacherInfoById", method = RequestMethod.GET)
    public ResultDTO<EmployeeEditInfoVo> getTeacherInfoById(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "老师表id", defaultValue = "29", required = true) @RequestParam(name = "id", required = true) Long id) {
        log.info("***********TeacherManageController.getTeacherInfoById******...apiVersion:{},Employee:{}", apiVersion, id);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            return new ResultDTO<>(teacherManageService.getTeacherInfoById(id, userDto));
        } catch (Exception e) {
            log.error("***********TeacherManageController.getTeacherInfoById******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "查询数量(启用数量)")
    @RequestMapping(value = "getTeacherCount", method = RequestMethod.GET)
    public ResultDTO<Map<String, Object>> getTeacherCount(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "组织ID", defaultValue = "1", required = true) @RequestParam(name = "orgId", required = true) Long orgId) {
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }
        try {
            HashMap<String, Object> params = new HashMap<>();
            if (null != orgId && 1 != orgId) {
                params.put("orgId",orgId);
            }
            return new ResultDTO<>(teacherManageService.getTeacherCount(params));
        } catch (Exception e) {
            log.error("***********ClassInfoManageController.page******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "查询老师分页列表")
    @RequestMapping(value = "/getTeacherInfoPageList", method = RequestMethod.GET)
    public ResultDTO<PageInfo<TeacherManageVo>> getTeacherInfoPageList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", defaultValue = "1", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "姓名", defaultValue = "邓敬源", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "手机号", defaultValue = "13603041430", required = false) @RequestParam(name = "mobile", required = false) String mobile,
            @ApiParam(value = "性别", defaultValue = "男", required = false) @RequestParam(name = "sex", required = false) String sex,
            @ApiParam(value = "职务/岗位", defaultValue = "2", required = false) @RequestParam(name = "positionId", required = false) Integer positionId,
            @ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        log.info("***********TeacherManageController.getTeacherInfoPageList******...apiVersion:{},orgId:{},name:{},mobile:{},sex:{},positionId:{},pageNo:{},pageSize:{}",
                apiVersion, orgId, name, mobile, sex, positionId, pageNo, pageSize);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }
        if (null == orgId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }
        try {
            HashMap<String, Object> params = new HashMap<>(5);
            if (null != orgId) {
                params.put("orgId", orgId);
            }
            if (!StringUtil.isNullOrBlank(name)) {
                params.put("name", name);
            }
            if (null != positionId) {
                params.put("positionId", positionId);
            }
            if (!StringUtil.isNullOrBlank(mobile)) {
                params.put("mobile", mobile);
            }
            if (!StringUtil.isNullOrBlank(sex)) {
                params.put("sex", sex);
            }

            return new ResultDTO<>(teacherManageService.getTeacherManageList(params, pageNo, pageSize));
        } catch (Exception e) {
            log.error("***********TeacherManageController.getTeacherInfoPageList******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "获取学校教师列表(包含园长)，排除非当前班级的班主任")
    @RequestMapping(value = "getTeacherListExcludeOtherMaster", method = RequestMethod.GET)
    public ResultDTO<List<TeacherManageVo>> getTeacherListExcludeOtherMaster(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true, defaultValue = "1") @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "班级ID", required = false, defaultValue = "1") @RequestParam(name = "classId", required = false) Long classId) {
        log.info("***********TeacherManageController.getTeacherListExcludeOtherMaster******apiVersion:{},orgId:{},classId:{}", apiVersion, orgId, classId);

        try {
            if (orgId == 0) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            return new ResultDTO<>(teacherManageService.getTeacherListExcludeOtherMaster(orgId, classId));
        } catch (Exception e) {
            log.error("***********TeacherManageController.getTeacherListExcludeOtherMaster******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "查询老师列表(不分页)")
    @RequestMapping(value = "/getTeacherInfoList", method = RequestMethod.GET)
    public ResultDTO<List<TeacherManageVo>> getTeacherInfoList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", defaultValue = "1", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "姓名", defaultValue = "邓敬源", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "手机号", defaultValue = "13603041430", required = false) @RequestParam(name = "mobile", required = false) String mobile,
            @ApiParam(value = "性别", defaultValue = "男", required = false) @RequestParam(name = "sex", required = false) String sex,
            @ApiParam(value = "职务/岗位: 1园长 2教师 3保育员 4 营养师 5代课教师 6其他", defaultValue = "2", required = false) @RequestParam(name = "userType", required = false) Short userType,
            @ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        log.info("***********TeacherManageController.getTeacherInfoList******...apiVersion:{},orgId:{},name:{},mobile:{},sex:{},userType:{},pageNo:{},pageSize:{}",
                apiVersion, orgId, name, mobile, sex, userType, pageNo, pageSize);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            HashMap<String, Object> params = new HashMap<>(5);
            if (null != orgId) {
                params.put("orgId", orgId);
            }
            if (null != name) {
                params.put("name", name);
            }
            if (null != userType) {
                params.put("userType", userType);
            }
            if (null != mobile) {
                params.put("mobile", mobile);
            }
            if (null != sex) {
                params.put("sex", sex);
            }
            return new ResultDTO<>(teacherManageService.getAllTeacherManageList(params));
        } catch (Exception e) {
            log.error("***********TeacherManageController.getTeacherInfoList******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "根据班级查询老师分页列表")
    @RequestMapping(value = "getEmployeeInfoPageByClassId", method = RequestMethod.GET)
    public ResultDTO<PageInfo<EmployeeInfoDto>> getEmployeeInfoPageByClassId(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true, defaultValue = "1") @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "班级ID", required = true, defaultValue = "1") @RequestParam(name = "classId", required = true) Long classId,
            @ApiParam(value = "页码", required = false, defaultValue = "1") @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false, defaultValue = "10") @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        log.info("***********TeacherManageController.getEmployeeInfoPageByClassId******apiVersion:{},orgId:{},classId:{}", apiVersion, orgId, classId);

        try {
            if (orgId == 0 || classId == 0) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            Map<String, Object> params = new HashMap<>(2);
            params.put("orgId", orgId);
            params.put("classId", classId);

            return new ResultDTO<>(teacherManageService.getEmployeeInfoPageByClassId(params, pageNo, pageSize));
        } catch (Exception e) {
            log.error("***********TeacherManageController.getEmployeeInfoPageByClassId******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    /**
     * 新学校导入列:{0=学校名称, 1=教师姓名*, 2=性别*, 3=岗位*, 4=手机号*, 5=出生日期, 6=教工号, 7=入职日期, 8=民族, 9=考勤卡号}
     * @param apiVersion
     * @param orgId
     * @param uploadFile
     * @return
     */
    @ApiOperation(value = "导入全校老师")
    @PostMapping(value = "importExcelFile")
    public ResultDTO importExcelFile(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true, defaultValue = "2995") @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "(new:新学校导入(包含k12导入))", required = true, defaultValue = "new") @RequestParam(name = "flag", required = true) String flag,
            @RequestParam("uploadFile") MultipartFile uploadFile) {
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        }
        InputStream in = null;
        try {
            if (null == orgId || StringUtils.isEmpty(flag) || null == uploadFile) {
                return new ResultDTO(ErrorCode.PARAM_MISSING);
            }
            if (uploadFile.isEmpty()) {
                log.error("---TeacherManageController.importExcelFile---文件不存在！");
                return new ResultDTO(ErrorCode.BUSINESS_DATA_WRONG);
            }
            //验证flag值,新学校只有7列数据,老学校有9列
            Integer columns = 0;
            if(!flag.equals("new")){
                return new ResultDTO(ErrorCode.PARAM_MISMATCH);
            }
            in = uploadFile.getInputStream();
            List<Object> excelData = EasyExcel.read(in).sheet().doReadSync();
            if (!CollectionUtils.isEmpty(excelData)) {
                Map mapTypes = (Map<String, Object>) excelData.get(1);
                columns = mapTypes.size();
                //获取List子集,从第二行开始获取,前面2行是标题行,只有第三行才是真正的数据行
                excelData = excelData.subList(2,excelData.size());
                List<Object[]> data = ObjectUtil.trans(excelData,columns);
                return preSave(userDto, orgId, data, flag,new Date());
            }
            return new ResultDTO(ErrorCode.BUSINESS_DATA_WRONG);
        }catch (RejectedExecutionException e) {
            log.error("----已达到线程池最大等待队列---",e);
            return new ResultDTO(ErrorCode.SYSTEM_THREAD_MAXQUEUE);
        } catch (Exception e) {
            log.error("----TeacherManageController.importExcelFile----", e);
            return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private ResultDTO<Object> preSave(UserDto userDto,Long orgId, List<Object[]> data,String flag,Date date) throws Exception{
        Integer total = data.size();
        Integer pageSize = PAGE_SIZE;
        Integer pages = (total + pageSize - 1) / pageSize;

        //缓存异步请求对象
        List<FutureTask<ResultDTO<Map<String,Object>>>> futureTaskList = new ArrayList<>();
        //获取线程池
        ExecutorService executorService = ThreadPoolUtil.getExecutorService();
        FutureTask<ResultDTO<Map<String,Object>>> future;
        Integer currentRow = 0;
        Boolean isClearAddressBook = true;
        if(data.size() > MAX_IMPORT_NUM_OF_CLEAR_ADDRESS_BOOK){//同时导入超过10条数据，就不再一个个去清理用户通讯录缓存
            isClearAddressBook = false;
        }
        for (int currentPage = 1; currentPage <= pages; currentPage++) {
            List<Object[]> dataList = ListUtil.pager(currentPage,pageSize,data);
            currentRow = (currentPage - 1) * pageSize + 4;
            future = new FutureTask<ResultDTO<Map<String,Object>>>(new ImportTeacherTask(teacherManageService,userDto,orgId,dataList,flag,currentRow,isClearAddressBook));
            executorService.execute(future);
            //缓存到集合中集中获取
            futureTaskList.add(future);
        }

        //同步集中获取处理结果
        Integer importOkNum = 0;
        Set<TeacherManageVo> totalFailList = new HashSet();
        if(futureTaskList.size() > 0){
            ResultDTO<Map<String,Object>> resultDto;
            for(FutureTask<ResultDTO<Map<String,Object>>> futureTask : futureTaskList){
                resultDto = futureTask.get();
                if(!resultDto.isSuccess()){
                    return new ResultDTO(resultDto.isSuccess(),resultDto.getErrorCode(),resultDto.getErrorMsg());
                }
                Map<String,Object> result = resultDto.getData();
                //log.info("----批量导入老师,FutureTask返回的oriResult------{}", JSONObject.toJSONString(result));
                List<TeacherManageVo> okList = (List<TeacherManageVo>)result.get("success");
                List<TeacherManageVo> failList = (List<TeacherManageVo>)result.get("fail");
                importOkNum = importOkNum + okList.size();
                totalFailList.addAll(failList);
            }
        }

        if(!isClearAddressBook) {
            //只清理教职工的通讯录缓存
            userOpenService.deleteRedisAddressBookByOrgId(orgId, UserTypeEnum.TEACHER.getValue());
        }

        /******************************IM相关开始***************************************/
        //新学校,批量导入学生,家长,在这里创建IM账号.2.0学校暂时不需要创建IM账号
/*        log.info("*****新学校,批量导入学生,家长********repairImClassGroup**************orgId={}", orgId);
        ImAutoClassIdByOrgIdTask imAutoClassIdByOrgIdTask = new ImAutoClassIdByOrgIdTask(orgId,userOpenService);
        ThreadPoolUtil.addTask(imAutoClassIdByOrgIdTask);*/
        /****************************IM相关结束***************************************/
        /*****************************导入用户XMPP统一处理开始***************************************/
        ThreadPoolUtil.addPoolTask(new XmppUpdatePersonByDateTask(orgId,date,xmppService,RoleTypeEnum.TEACHER.getValue()));
        /*****************************导入用户XMPP统一处理结束***************************************/

        log.info("----批量导入老师,最终导入结果---totalFailList={}",JSONObject.toJSONString(totalFailList));
        //序列化字段
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String outJson = mapper.writeValueAsString(totalFailList);
        log.info("----批量导入老师,最终成功导入{}条数据----",importOkNum);
        log.info("----批量导入老师,最终导入totalFailList结果,Json格式:---{}",outJson);

        Map<String,Object> returnMap = new HashMap();
        returnMap.put("importOkNum",importOkNum);
        returnMap.put("importFailList",totalFailList);
        return new ResultDTO(returnMap);
    }

    @ApiOperation(value = "导出老师列表")
    @RequestMapping(value = "/exportTeacherExcel", method = RequestMethod.GET)
    public ResultDTO exportTeacherExcel(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", defaultValue = "1", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "姓名", defaultValue = "邓敬源", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "手机号", defaultValue = "13603041430", required = false) @RequestParam(name = "mobile", required = false) String mobile,
            @ApiParam(value = "性别", defaultValue = "男", required = false) @RequestParam(name = "sex", required = false) String sex,
            @ApiParam(value = "职务/岗位", defaultValue = "2", required = false) @RequestParam(name = "positionId", required = false) Integer positionId,
            @ApiParam(value = "登录token", required = false) @RequestParam(name = "token", required = false) String token,
            HttpServletResponse response
    ) {
        log.info("***********TeacherManageController.exportTeacherExcel******...apiVersion:{},orgId:{},name:{},mobile:{},sex:{},positionId:{}",
                apiVersion, orgId, name, mobile, sex, positionId);

//        UserDto userDto = getUserByLogin(token);
//        if (userDto == null) {
//            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
//        }
        if (null == orgId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }
        try {
            HashMap<String, Object> params = new HashMap<>(5);
            if (null != orgId) {
                params.put("orgId", orgId);
            }
            if (!StringUtil.isNullOrBlank(name)) {
                params.put("name", name);
            }
            if (null != positionId) {
                params.put("positionId", positionId);
            }
            if (!StringUtil.isNullOrBlank(mobile)) {
                params.put("mobile", mobile);
            }
            if (!StringUtil.isNullOrBlank(sex)) {
                params.put("sex", sex);
            }

            List<Object[]> dataList = teacherManageService.exportTeacherExcel(params, orgId);
            if(org.apache.commons.collections.CollectionUtils.isEmpty(dataList)){
                return  new ResultDTO<>(ErrorCode.NOT_DATA);
            }

            ExcelUtil.exportAttendExcel("sheet1", getExportTeacherExcel(),getExportTeacherHeader(), dataList, response);
            return null;
        } catch (Exception e) {
            log.error("***********TeacherManageController.getTeacherInfoPageList******", e);
            return new ResultDTO<>(false);
        }
    }

    private String getExportTeacherExcel(){
        return "老师"+TimeUtil.toStringYYYY_MM_DD(new Date())+ "导出";
    }

    /**
     * 获取表头getBoarderMonthHeaders
     * @return 表头集合
     */
    public String[] getExportTeacherHeader(){
        List<String> headers = new ArrayList<>();
        headers.add("学校名称");
        //教师excle标头
        headers.add("老师姓名");
        headers.add("岗位");
        headers.add("老师手机号");
        headers.add("教工号");
        headers.add("考勤卡卡号");
        headers.add("人脸照片");
        headers.add("人脸录入/修改时间");
        String[] temp={};
        return headers.toArray(temp);
    }
}
